<?php include_once 'header.php'; ?>
<div class="row">
    <div class="col-md-12">

        <div class="card shadow">
            <div class="card-body">
                <div class="toolbar">
                    <form class="form">
                        <div class="form-row">
                            <div class="form-group col-auto mr-auto">
                                <button type="button" class="btn btn-danger" data-toggle="modal" data-target="#add"><i
                                            class="fe fe-plus fe-12 mr-2"></i><span class="small">添加卡密</span>
                                </button>
                                <button type="button" class="btn btn-warning" data-toggle="modal" data-target="#reward">
                                    <i class="fe fe-gift fe-12 mr-2"></i><span class="small">发放奖励</span></button>
                            </div>

                            <div class="form-group col-auto col-md-3">
                                <div class="input-group so">
                                    <input type="text" class="form-control" placeholder="输入搜索内容" id="so">
                                    <div class="input-group-append">
                                        <button class="btn btn-primary" type="button" id="so_submit">搜索</button>
                                    </div>
                                </div>
                            </div>
                        </div>
                    </form>
                </div>
                <div class="table-responsive">
                    <table class="table table-borderless table-hover mb-0">
                        <thead>
                        <tr>
                            <th class="wd-20">
                                ID
                            </th>
                            <th class="wd-20">
                                卡密/备注
                            </th>
                            <th class="wd-20">
                                应用
                            </th>
                            <th class="wd-20">
                                在线
                            </th>
                            <th class="wd-20">
                                面值
                            </th>
                            <th class="wd-20">
                                使用时间
                            </th>
                            <th class="wd-20">
                                创建时间
                            </th>
                            <th class="wd-20">
                                导出状态
                            </th>
                            <th class="wd-20">
                                状态
                            </th>
                            <th class="wd-20">
                                管理
                            </th>
                        </tr>
                        </thead>
                        <tbody id="tbody_list">


                        </tbody>
                    </table>
                </div>
                <nav class="mb-0">
                    <ul class="pagination justify-content-center mb-0" id="poge_list_ul">

                    </ul>
                </nav>

            </div>
        </div>
    </div>
</div>

<div class="modal fade" id="add" tabindex="-1" role="dialog" aria-hidden="true" data-backdrop="static"
     data-keyboard="false">
    <div class="modal-dialog" role="document">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title">
                    添加卡密
                </h5>
                <button type="button" class="close" data-dismiss="modal" aria-label="Close">
                    <span aria-hidden="true">&times;</span>
                </button>
            </div>
            <div class="modal-body">
                <form>
                    <div class="form-group">
                        <label>卡密分组</label>
                        <div class="float-right">
                            <a href="javascript:get_kmg_data();" id="add_kami_group_refresh">刷新</a>
                        </div>
                        <select class="form-control" id="add_kmg">

                        </select>
                    </div>

                    <div class="form-group">
                        <label>卡密备注</label>
                        <input type="text" class="form-control" placeholder="如：活动卡密（可空）" id="add_km_note">
                    </div>
                    <div class="form-group">
                        <label>卡密长度<span class="fe fe-help-circle ml-1" data-toggle="tooltip"
                                             title="可自定义卡密长度，为安全起见，卡密长度仅可在16~32位字符区间"></span></label>
                        <input type="number" class="form-control" placeholder="卡密长度16~32区间" id="add_km_length"
                               value="18">
                    </div>
                    <div class="form-group">
                        <label>卡密前缀<span class="fe fe-help-circle ml-1" data-toggle="tooltip"
                                             title="卡密前缀有助于区分卡密，支持字母、数字、下划线(_)、横杠(-)"></span></label>
                        <input type="text" class="form-control" placeholder="如：TK-（可空）" id="add_km_pre">
                    </div>

                    <div class="form-group">
                        <label>生成数量<span class="fe fe-help-circle ml-1" data-toggle="tooltip"
                                             title="一次性最多生成1万张"></span></label>
                        <div class="float-right" id="modal_vip_free_div">
                            <div class="custom-control custom-checkbox">
                                <input type="checkbox" class="custom-control-input" id="add_out">
                                <label class="custom-control-label" for="add_out">生成后立即导出</label>
                            </div>
                        </div>
                        <div class="input-group">
                            <input type="number" class="form-control" placeholder="1" id="add_num" value="1">
                            <div class="input-group-append">
                                <span class="input-group-text">张</span>
                            </div>
                        </div>
                    </div>

                    <div class="form-group mb-2">
                        <button type="submit" class="btn btn-primary btn-block" id="add_submit">提交</button>
                    </div>
                </form>
            </div>
        </div>
    </div>
</div>

<div class="modal fade" id="reward" tabindex="-1" role="dialog" aria-hidden="true" data-backdrop="static"
     data-keyboard="false">
    <div class="modal-dialog" role="document">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title">
                    发放奖励
                </h5>
                <button type="button" class="close" data-dismiss="modal" aria-label="Close">
                    <span aria-hidden="true">&times;</span>
                </button>
            </div>
            <div class="modal-body">
                <form>
                    <div class="form-group">
                        <label>卡密分组</label>
                        <div class="float-right">
                            <a href="javascript:get_kmg_data();" id="reward_kami_group_refresh">刷新</a>
                        </div>
                        <select class="form-control" id="reward_kmg">
                            <option value="0">全部</option>
                        </select>
                    </div>

                    <div class="form-group">
                        <label>奖励时长<span class="fe fe-help-circle ml-1" data-toggle="tooltip"
                                             title="奖励时长仅针对VIP未过期的卡密有效"></span></label>
                        <div class="input-group">
                            <input type="number" class="form-control" placeholder="1" id="reward_val" value="1">
                            <div class="input-group-append">
                                <select id="reward_val_type" class="form-control">
                                    <option value="s">秒</option>
                                    <option value="i">分</option>
                                    <option value="h">时</option>
                                    <option value="d">天</option>
                                </select>
                            </div>
                        </div>
                    </div>

                    <div class="form-group mb-2">
                        <button type="submit" class="btn btn-primary btn-block" id="reward_submit">提交</button>
                    </div>
                </form>
            </div>
        </div>
    </div>
</div>


<div class="modal fade modal-right modal-slide" id="edit" tabindex="-1" role="dialog" aria-hidden="true"
     data-backdrop="static" data-keyboard="false">
    <div class="modal-dialog modal-plus-min" role="document">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title">
                    编辑卡密
                </h5>
                <button type="button" class="close" data-dismiss="modal" aria-label="Close">
                    <span aria-hidden="true">&times;</span>
                </button>
            </div>
            <div class="modal-body bg-light">
                <form>
                    <div class="row mb-3">
                        <div class="col-sm-12">
                            <!-- Profile -->
                            <div class="card bg-primary">
                                <div class="card-body profile-user-box">
                                    <div class="row">
                                        <div class="col-12">
                                            <div class="row align-items-center">
                                                <div class="col-12">
                                                    <div class="row">
                                                        <div class="col-auto mr-auto">
                                                            <h5 class="mt-1 mb-0 text-white" id="edit_cardNo">
                                                                YK-2D3657C4F36ACR4SZT</h5>
                                                        </div>
                                                        <div class="col-auto col-md-3">
                                                            <div class="text-end pt-1"><small
                                                                        class="badge badge-pill text-white bg-primary-dark"
                                                                        id="edit_kmGroup">天卡</small></div>
                                                        </div>
                                                    </div>
                                                    <p class="font-13 text-white-50">卡号</p>

                                                    <ul class="mb-0 list-inline">
                                                        <li class="list-inline-item me-3">
                                                            <h6 class="mb-0 text-white" id="edit_setTime">2022-10-27
                                                                18:05</h6>
                                                            <p class="mb-0 font-13 text-white-50">创建时间</p>
                                                        </li>
                                                        <li class="list-inline-item">
                                                            <h6 class="mb-0 text-white" id="edit_setIP">
                                                                38.94.109.28</h6>
                                                            <p class="mb-0 font-13 text-white-50">创建IP</p>
                                                        </li>
                                                    </ul>
                                                </div>
                                            </div>
                                        </div>
                                    </div> <!-- end row -->
                                </div> <!-- end card-body/ profile-user-box-->
                            </div><!--end profile/ card -->
                        </div> <!-- end col-->
                    </div>
                    <div class="row">
                        <div class="col-md-12">
                            <div class="card mb-3">
                                <div class="card-body">
                                    <form>
                                        <div class="form-group">
                                            <label>客户端最大值<span class="fe fe-help-circle ml-1"
                                                                     data-toggle="tooltip"
                                                                     title="可设置该组卡密允许绑定多少台设备，如：3，则该组卡密可以同时绑定3台设备使用，0则表示不限"></span></label>
                                            <div class="input-group">
                                                <input type="number" class="form-control" placeholder="1"
                                                       id="edit_clientmax" value="1">
                                                <div class="input-group-append">
                                                    <span class="input-group-text">台</span>
                                                </div>
                                            </div>
                                        </div>
                                        <div class="form-group">
                                            <label>会员到期</label>
                                            <div class="float-right">
                                                <div class="custom-control custom-checkbox">
                                                    <input type="checkbox" class="custom-control-input"
                                                           id="edit_vip_long"
                                                           onclick="checked_vip('edit',this.checked);">
                                                    <label class="custom-control-label"
                                                           for="edit_vip_long">永久会员</label>
                                                </div>
                                            </div>
                                            <input type="datetime-local" id="edit_vipExp" class="form-control">
                                        </div>
                                    </form>
                                </div> <!-- end card-body -->
                            </div> <!-- end card-->


                            <div class="card mb-3">
                                <div class="card-body">
                                    <form>
                                        <div class="form-group" hidden>
                                            <label>卡密ID</label>
                                            <input type="number" class="form-control" id="edit_id" placeholder="1">
                                        </div>
                                        <div class="form-group">
                                            <label>备注<span class="fe fe-help-circle ml-1" data-toggle="tooltip"
                                                             title="给卡密备注能够方便的管理卡密"></span></label>
                                            <input type="text" class="form-control" id="edit_cardNote"
                                                   placeholder="卡密备注">
                                        </div>
                                        <div class="form-group">
                                            <label>绑定邮箱<span class="fe fe-help-circle ml-1" data-toggle="tooltip"
                                                                 title="邮箱设置方法：用户注册API、用户绑定API，不可编辑"></span></label>
                                            <input type="email" class="form-control" id="edit_cardEmail"
                                                   placeholder="电子邮箱" readonly>
                                        </div>
                                        <div class="form-group">
                                            <label>密码</label>
                                            <input type="text" class="form-control" id="edit_cardPwd"
                                                   placeholder="空则不修改密码">
                                        </div>

                                        <div class="form-group">
                                            <div class="float-left">
                                                <div class="custom-switch">
                                                    <input type="checkbox" class="custom-control-input" id="edit_state"
                                                           onchange="checked_ban(this.checked);">
                                                    <label class="custom-control-label" for="edit_state"></label>
                                                </div>
                                            </div>
                                            <label>禁用卡密期限</label>
                                            <div class="float-right" id="edit_ban_long_div" hidden>
                                                <div class="custom-control custom-checkbox">
                                                    <input type="checkbox" class="custom-control-input"
                                                           id="edit_ban_long"
                                                           onclick="checked_ban(this.checked,'long');">
                                                    <label class="custom-control-label"
                                                           for="edit_ban_long">永久禁用</label>
                                                </div>
                                            </div>
                                            <input type="datetime-local" id="edit_banExp" class="form-control" readonly>
                                        </div>

                                        <div class="form-group" id="ban_notice_div" hidden>
                                            <label>禁用通知</label>
                                            <textarea class="form-control" id="edit_banMsg" rows="4"
                                                      placeholder="如：违反用户使用协议，禁用中"></textarea>
                                        </div>

                                        <div class="text-center mt-3">
                                            <button class="btn btn-primary btn-block" type="submit" id="edit_submit">
                                                确认编辑
                                            </button>
                                        </div>
                                    </form>
                                </div> <!-- end card-body -->
                            </div> <!-- end card -->
                        </div> <!-- end col -->

                        <div class="col-md-12">
                            <div class="card">
                                <div class="card-body">
                                    <ul class="nav nav-pills nav-fill mb-3" id="myTab" role="tablist">
                                        <li class="nav-item">
                                            <a class="nav-link active" data-toggle="tab" href="#log" role="tab"
                                               aria-selected="true">
                                                用户日志
                                            </a>
                                        </li>
                                        <li class="nav-item">
                                            <a class="nav-link" data-toggle="tab" href="#client" role="tab"
                                               aria-selected="false">
                                                绑定设备
                                            </a>
                                        </li>
                                    </ul>
                                    <div class="tab-content" id="myTabContent">
                                        <div class="tab-pane fade show active" id="log" role="tabpanel">
                                            <div class="p-4" id="logs_state">
                                                <div class="text-center mt-5 mb-5">
                                                    <div class="avatar avatar-lg">
                                                        <img src="/assets/images/null.png" class="avatar-img"
                                                             style="width: 100px;">
                                                    </div>
                                                    <div class="card-text">
                                                        <strong class="card-title my-0">
                                                            暂无日志
                                                        </strong>
                                                        <p class="small text-muted mb-5">
                                                            There's a little problem
                                                        </p>
                                                    </div>
                                                </div>
                                            </div>
                                            <div class="table-responsive" id="logs_table" hidden>
                                                <table class="table table-hover table-borderless table-striped">
                                                    <thead>
                                                    <tr>
                                                        <th>
                                                            操作类型
                                                        </th>
                                                        <th>
                                                            时间/IP
                                                        </th>
                                                        <th class="wd-20">
                                                            状态
                                                        </th>
                                                    </tr>
                                                    </thead>
                                                    <tbody id="tbody_logs">

                                                    </tbody>
                                                </table>
                                            </div>
                                        </div>
                                        <div class="tab-pane fade" id="client" role="tabpanel">
                                            <div class="p-4" id="client_state">
                                                <div class="text-center mt-5 mb-5">
                                                    <div class="avatar avatar-lg">
                                                        <img src="/assets/images/null.png" class="avatar-img"
                                                             style="width: 100px;">
                                                    </div>
                                                    <div class="card-text">
                                                        <strong class="card-title my-0">
                                                            暂未绑定任何设备
                                                        </strong>
                                                        <p class="small text-muted mb-5">
                                                            There's a little problem
                                                        </p>
                                                    </div>
                                                </div>
                                            </div>
                                            <div class="table-responsive" id="client_table" hidden>
                                                <table class="table table-hover table-borderless table-striped mt-n3 mb-n1">
                                                    <thead>
                                                    <tr>
                                                        <th class="text-left">
                                                            设备标识/时间
                                                        </th>
                                                        <th class="wd-20">
                                                            操作
                                                        </th>
                                                    </tr>
                                                    </thead>
                                                    <tbody id="tbody_client">

                                                    </tbody>
                                                </table>
                                            </div>
                                        </div>
                                    </div>
                                </div>
                            </div> <!-- end card-->
                        </div><!-- end col-->
                    </div>
                </form>
            </div>

        </div>
    </div>
</div>

<div id="del" class="modal fade" tabindex="-1" role="dialog" aria-hidden="true">
    <div class="modal-dialog modal-sm">
        <div class="modal-content">
            <div class="modal-body p-4">
                <div class="text-center">
                    <h4 class="mt-2">删除警告</h4>
                    <p class="mt-3">确认删除卡密组：<strong class="text-danger me-1" id="del_name">null</strong> ？<br>删除后不可恢复！请慎重操作
                    </p>
                    <input type="number" class="form-control" id="del_id" placeholder="1" hidden>
                    <button type="button" class="btn btn-danger mr-2 my-2" id="del_submit">确认删除</button>
                    <button type="button" class="btn btn-light" data-dismiss="modal">取消删除</button>
                </div>
            </div>
        </div><!-- /.modal-content -->
    </div><!-- /.modal-dialog -->
</div><!-- /.modal -->
<script>
    function init(act, pg) {
        initAct = act;
        initPg = pg;
        $.ajax({
            cache: false,
            type: "POST",
            data: {
                act,
                pg
            },
            dataType: "json",
            success: function (data) {
                if (data.code == 200) {
                    add_list(data.data.list);
                    if (data.data.pageList) {
                        page_list(data.data.pageList, data.data.currentPage, data.data.maxPage)
                    }
                    loading_end(true, null)
                } else {
                    loading_end(false, data.msg, true)
                }
            },
            error: function (XMLHttpRequest, textStatus, errorThrown) {
                loading_end(false, textStatus, true)
            }
        });
        get_kmg_data();
        return false
    }

    function get_kmg_data() {
        $("#add_kami_group_refresh").html('<i class="spinner-ui fe fe-rotate-cw fe-12 mr-2"></i>刷新中');
        $("#reward_kami_group_refresh").html('<i class="spinner-ui fe fe-rotate-cw fe-12 mr-2"></i>刷新中');
        $.ajax({
            cache: false,
            type: "POST",
            data: {
                act: "get_kmg"
            },
            dataType: "json",
            success: function (data) {
                if (data.code == 200) {
                    var list = data.data.list;
                    if (list.length >= 1) {
                        $("#add_kmg").empty();
                        $("#reward_kmg").empty();
                        $("#reward_kmg").append('<option value="0">全部</option>')
                    } else {
                        $("#add_kmg").append('<option value="0">请先添加卡密组</option>')
                    }
                    for (var i = 0; i < list.length; i++) {
                        $("#add_kmg").append('<option value="' + list[i].id + '">' + list[i].name + "</option>");
                        $("#reward_kmg").append('<option value="' + list[i].id + '">' + list[i].name + "</option>")
                    }
                }
                $("#add_kami_group_refresh").html("刷新");
                $("#reward_kami_group_refresh").html("刷新")
            },
            error: function (XMLHttpRequest, textStatus, errorThrown) {
                $("#add_kami_group_refresh").html("刷新");
                $("#reward_kami_group_refresh").html("刷新")
            }
        });
        return false
    }

    $("#add_submit").click(function () {
        var submit_data = {
            act: "add"
        };
        submit_data.gid = $("#add_kmg").val();
        submit_data.note = $("#add_km_note").val();
        submit_data.length = $("#add_km_length").val();
        submit_data.pre = $("#add_km_pre").val();
        submit_data.num = $("#add_num").val();
        submit_data.out = $("#add_out").prop("checked") ? "y" : "n";
        $("#add_submit").html('<i class="spinner-ui fe fe-rotate-cw fe-12 mr-2"></i>正在提交');
        $("#add_submit").attr("disabled", true);
        $.ajax({
            cache: false,
            type: "POST",
            data: submit_data,
            dataType: "json",
            success: function (data) {
                $("#add_submit").html("确认添加");
                $("#add_submit").attr("disabled", false);
                if (data.code == 200) {
                    init(initAct, initPg);
                    if (submit_data.out == "y") {
                        window.location.href = data.data.downUrl
                    }
                    $("#add_km_note").val("");
                    $("#add_out").prop("checked", false);
                    $("#add_num").val("1");
                    $("#add").modal("hide")
                } else {
                    cocoMessage.error(data.msg, 2000)
                }
            }
        });
        return false
    });
    $("#reward_submit").click(function () {
        var submit_data = {
            act: "reward"
        };
        submit_data.reward_kmg = $("#reward_kmg").val();
        submit_data.reward_val = timeTos($("#reward_val").val(), $("#reward_val_type").val());
        $("#reward_submit").html('<i class="spinner-ui fe fe-rotate-cw fe-12 mr-2"></i>正在提交');
        $("#reward_submit").attr("disabled", true);
        $.ajax({
            cache: false,
            type: "POST",
            data: submit_data,
            dataType: "json",
            success: function (data) {
                $("#reward_submit").html("确认添加");
                $("#reward_submit").attr("disabled", false);
                if (data.code == 200) {
                    cocoMessage.success(data.msg, 2000);
                    $("#reward_val").val("");
                    $("#reward").modal("hide")
                } else {
                    cocoMessage.error(data.msg, 2000)
                }
            }
        });
        return false
    });
    $("#edit_submit").click(function () {
        var submit_data = {
            act: "edit"
        };
        submit_data.id = $("#edit_id").val();
        var vip = $("#edit_vipExp").val();
        var vip_long = $("#edit_vip_long").prop("checked") ? true : false;
        if (vip_long) {
            submit_data.vipExp = 9999999999
        } else {
            var viptime = Date.parse(vip) / 1000;
            if (isEmpty(viptime) || viptime < time()) {
                submit_data.vipExp = 0
            } else {
                submit_data.vipExp = viptime
            }
        }
        var state = $("#edit_state").prop("checked") ? true : false;
        var ban_long = $("#edit_ban_long").prop("checked") ? true : false;
        if (state) {
            if (ban_long) {
                submit_data.banExp = 9999999999
            } else {
                var banExp = $("#edit_banExp").val();
                var bantime = Date.parse(banExp) / 1000;
                if (isEmpty(bantime) || bantime < time()) {
                    submit_data.banExp = 0
                } else {
                    submit_data.banExp = bantime
                }
            }
        } else {
            submit_data.banExp = 0
        }
        submit_data.banMsg = $("#edit_banMsg").val();
        submit_data.clientmax = $("#edit_clientmax").val();
        submit_data.note = $("#edit_cardNote").val();
        var pwd = $("#edit_cardPwd").val();
        if (!isEmpty(pwd)) {
            submit_data.password = pwd
        }
        $("#edit_submit").html('<i class="spinner-ui fe fe-rotate-cw fe-12 mr-2"></i>正在提交');
        $("#edit_submit").attr("disabled", true);
        $.ajax({
            cache: false,
            type: "POST",
            data: submit_data,
            dataType: "json",
            success: function (data) {
                $("#edit_submit").html("确认编辑");
                $("#edit_submit").attr("disabled", false);
                if (data.code == 200) {
                    cocoMessage.success("编辑成功", 2000);
                    update_list(data.data.list[0]);
                    $("#edit").modal("hide")
                } else {
                    cocoMessage.error(data.msg, 2000)
                }
            }
        });
        return false
    });
    $("#del_submit").click(function () {
        var del_id = $("#del_id").val();
        $("#del_submit").html('<i class="spinner-ui fe fe-rotate-cw fe-12 mr-2"></i>正在删除');
        $("#del_submit").attr("disabled", true);
        $.ajax({
            cache: false,
            type: "POST",
            data: {
                act: "del",
                id: del_id
            },
            dataType: "json",
            success: function (data) {
                $("#del_submit").html("确认删除");
                $("#del_submit").attr("disabled", false);
                if (data.code == 200) {
                    $("#list_" + del_id).remove();
                    cocoMessage.success(data.msg, 2000);
                    $("#del").modal("hide");
                    var tbody = $("#tbody_list").children();
                    if (tbody.length < 1) {
                        init(initAct, initPg)
                    }
                } else {
                    cocoMessage.error(data.msg, 2000)
                }
            }
        });
        return false
    });

    function nearest_client(clientID) {
        if (!clientID){
            return [null, null]
        }
        let dataList = JSON.parse(clientID)
        let nearestLoginTime = null;
        let nearestClient = null;
        let currentTime = Math.floor(Date.now() / 1000);
        let minTimeDiff = Infinity;

        dataList.forEach(item => {
            let timeDiff = currentTime - item.login_time;
            if (timeDiff >= 0 && timeDiff < minTimeDiff) {
                minTimeDiff = timeDiff;
                nearestLoginTime = item.login_time;
                nearestClient = item.udid;
            }
        });
        if (nearestLoginTime !== null) {
            let minutesDiff = Math.floor(minTimeDiff / 60);
            if (minutesDiff > 30) {
                return [null, null]
            } else {
                return [nearestClient, nearestLoginTime]
            }
        } else {
            return [null, null]
        }
    }

    function add_list(list, empty = true, prepend = false) {
        if (empty) {
            $("#tbody_list").empty()
        }
        for (var i = 0; i < list.length; i++) {
            var data = "<td>" + list[i].id + "</td>";
            data += '<td><p class="mb-0">' + list[i].cardNo + '</p><small class="mb-0 text-muted">' + list[i].cardNote + "</small></td>";
            // data += "<td>" + list[i].app_id + "</td>";
            // TODO: 这里可能有bug
            var appName = <?= json_encode($this->app['app_name']) ?>;
            data += "<td>" + appName + "</td>";

            let [nearestClient, nearestLoginTime] = nearest_client(list[i].clientID)
            data += "<td " + (!isEmpty(nearestLoginTime) ? 'data-toggle="tooltip" data-html="true" title="心跳时间：' + timeToDate(nearestLoginTime) + '<br />心跳设备：' + nearestClient + '"': '') + ">"+ '<span class="dot dot-lg bg-' + (!isEmpty(nearestLoginTime) ? "success" : "danger") + '"></span></td>';

            data += '<td data-toggle="tooltip" title="分组: ' + list[i].Gname + '">' + valTotype(list[i].cardVal) + "</td>";
            data += "<td " + (!isEmpty(list[i].useTime) ? 'data-toggle="tooltip" title="' + (!isEmpty(list[i].useID) ? "使用者：" + list[i].useID : "到期：" + (list[i].vipExp == 9999999999 ? "永久" : timeToDate(list[i].vipExp))) + '"' : "") + ">" + (isEmpty(list[i].useTime) ? "未使用" : timeToDate(list[i].useTime)) + "</td>";
            data += '<td data-toggle="tooltip" title="创建IP：' + list[i].setIP + '">' + timeToDate(list[i].setTime) + "</td>";
            data += "<td " + (!isEmpty(list[i].outTime) ? 'data-toggle="tooltip" title="导出时间：' + timeToDate(list[i].outTime) + '"' : "") + ">" + (!isEmpty(list[i].outTime) ? "已导出" : "未导出") + "</td>";
            data += '<td><span class="dot dot-lg bg-' + (isEmpty(list[i].banExp) && list[i].banExp < time() ? "success" : "danger") + '"></span></td>';
            data += '<td><button type="button" class="btn btn-primary btn-sm mr-1" data-toggle="modal" data-target="#edit" onclick="edit_list(\'' + encodeURI(JSON.stringify(list[i])) + '\');"><i class="fe fe-edit fe-12 mr-2"></i><span class="small">编辑</span></button><button type="button" class="btn btn-danger btn-sm" onclick="del_list(' + list[i].id + ",'" + list[i].cardNo + '\');"><i class="fe fe-trash-2 fe-12 mr-2"></i><span class="small">删除</span></button></td>';
            if (prepend) {
                $("#tbody_list").prepend('<tr id="list_' + list[i].id + '">' + data + "</tr>");
                var tbody = $("#tbody_list").children()
            } else {
                $("#tbody_list").append('<tr id="list_' + list[i].id + '">' + data + "</tr>")
            }
        }
        $('[data-toggle="tooltip"]').tooltip()
    }

    function update_list(list) {
        var data = "<td>" + list.id + "</td>";
        data += '<td class="text-left"><p class="mb-0">' + list.cardNo + '</p><small class="mb-0 text-muted">' + list.cardNote + "</small></td>";
        var appName = <?= json_encode($this->app['app_name']) ?>;
        data += "<td>" + appName + "</td>";
        let [nearestClient, nearestLoginTime] = nearest_client(list.clientID)
        data += "<td " + (!isEmpty(nearestLoginTime) ? 'data-toggle="tooltip" data-html="true" title="心跳时间：' + timeToDate(nearestLoginTime) + '<br />心跳设备：' + nearestClient + '"': '') + ">"+ '<span class="dot dot-lg bg-' + (!isEmpty(nearestLoginTime) ? "success" : "danger") + '"></span></td>';

        data += '<td data-toggle="tooltip" title="分组: ' + list.Gname + '">' + valTotype(list.cardVal) + "</td>";
        data += "<td " + (!isEmpty(list.useTime) ? 'data-toggle="tooltip" title="' + (!isEmpty(list.useID) ? "使用者：" + list.useID : "到期：" + (list.vipExp == 9999999999 ? "永久" : timeToDate(list.vipExp))) + '"' : "") + ">" + (isEmpty(list.useTime) ? "未使用" : timeToDate(list.useTime)) + "</td>";
        data += '<td data-toggle="tooltip" title="创建IP：' + list.setIP + '">' + timeToDate(list.setTime) + "</td>";
        data += "<td " + (!isEmpty(list.outTime) ? 'data-toggle="tooltip" title="导出时间：' + timeToDate(list.outTime) + '"' : "") + ">" + (!isEmpty(list.outTime) ? "已导出" : "未导出") + "</td>";
        data += '<td><span class="dot dot-lg bg-' + (isEmpty(list.banExp) && list.banExp < time() ? "success" : "danger") + '"></span></td>';
        data += '<td><button type="button" class="btn btn-primary btn-sm mr-1" data-toggle="modal" data-target="#edit" onclick="edit_list(\'' + encodeURI(JSON.stringify(list)) + '\');"><i class="fe fe-edit fe-12 mr-2"></i><span class="small">编辑</span></button><button type="button" class="btn btn-danger btn-sm" onclick="del_list(' + list.id + ",'" + list.cardNo + '\');"><i class="fe fe-trash-2 fe-12 mr-2"></i><span class="small">删除</span></button></td>';
        $("#list_" + list.id).html(data);
        $('[data-toggle="tooltip"]').tooltip()
    }

    function del_list(id, name) {
        $("#del_name").html(name);
        $("#del_id").val(id);
        $("#del").modal("show")
    }

    function edit_list(list) {
        var udata = decodeURI(list);
        var data = JSON.parse(udata.replace(/\n/g, "\\n").replace(/\r/g, "\\r"));
        $("#edit_id").val(data.id);
        $("#edit_cardPwd").val("");
        $("#edit_cardNo").html(data.cardNo);
        $("#edit_setTime").html(timeToDate(data.setTime));
        $("#edit_setIP").html(data.setIP);
        $("#edit_kmGroup").html(data.Gname);
        if (data.vipExp >= 9999999999) {
            $("#edit_vipExp").attr("data", "");
            $("#edit_vip_long").prop("checked", true);
            $("#edit_vipExp").attr("type", "text");
            $("#edit_vipExp").val("9999-99-99 99:99:99");
            $("#edit_vipExp").attr("readonly", true)
        } else if (data.vipExp > time()) {
            $("#edit_vip_long").prop("checked", false);
            var vip = timeToDate(data.vipExp, true);
            $("#edit_vipExp").attr("data", vip);
            $("#edit_vipExp").attr("type", "datetime-local");
            $("#edit_vipExp").val(vip);
            $("#edit_vipExp").attr("readonly", false)
        } else {
            $("#edit_vipExp").attr("data", "");
            $("#edit_vip_long").prop("checked", false);
            $("#edit_vipExp").attr("type", "datetime-local");
            $("#edit_vipExp").val("");
            $("#edit_vipExp").attr("readonly", false)
        }
        $("#edit_clientmax").val(data.clientMax);
        $("#edit_cardNote").val(data.cardNote);
        $("#edit_cardEmail").val(data.cardEmail);
        $("#edit_banExp").attr("data", data.banExp);
        if (data.banExp >= 9999999999) {
            $("#edit_state").prop("checked", true);
            checked_ban(true);
            checked_ban(true, "long");
            $("#edit_ban_long").prop("checked", true)
        } else if (data.banExp > time()) {
            $("#edit_state").prop("checked", true);
            checked_ban(true);
            checked_ban(false, "long")
        } else {
            checked_ban(false);
            $("#edit_state").prop("checked", false)
        }
        $("#edit_banMsg").val(data.banMsg);
        if (!isEmpty(data.clientID)) {
            add_client(JSON.parse(data.clientID))
        } else {
            add_client([])
        }
        get_logs(data.id)
    }

    function checked_vip(i, c) {
        if (c) {
            var vip = "9999-99-99 99:99:99";
            $("#" + i + "_vipExp").attr("type", "text");
            $("#" + i + "_vipExp").val(vip)
        } else {
            var vip = i == "edit" ? $("#edit_vipExp").attr("data") : timeToDate(null, true);
            $("#" + i + "_vipExp").attr("type", "datetime-local");
            $("#" + i + "_vipExp").val(vip)
        }
        $("#" + i + "_vipExp").attr("readonly", c)
    }

    function checked_ban(c, id = null) {
        if (id == "long") {
            if (c) {
                var t = "9999-99-99 99:99:99";
                $("#edit_banExp").attr("type", "text");
                $("#edit_banExp").val(t);
                $("#edit_banExp").attr("readonly", true)
            } else {
                $("#edit_banExp").attr("type", "datetime-local");
                var data = $("#edit_banExp").attr("data");
                if (data > 0) {
                    var times = timeToDate(data, true);
                    $("#edit_banExp").val(times)
                } else {
                    $("#edit_banExp").val("")
                }
            }
            $("#edit_banExp").attr("readonly", c)
        } else {
            $("#edit_banExp").attr("type", "datetime-local");
            $("#edit_banExp").val("");
            $("#edit_banExp").attr("readonly", c ? false : true);
            $("#ban_notice_div").attr("hidden", c ? false : true);
            $("#edit_ban_long").prop("checked", false);
            $("#edit_ban_long_div").attr("hidden", c ? false : true);
            if (c) {
                var data = $("#edit_banExp").attr("data");
                if (data > time()) {
                    if (data >= 9999999999) {
                        var t = "9999-99-99 99:99:99";
                        $("#edit_banExp").attr("type", "text");
                        $("#edit_banExp").val(t);
                        $("#edit_banExp").attr("readonly", true);
                        $("#edit_ban_long").prop("checked", true)
                    } else {
                        var times = timeToDate(data, true);
                        $("#edit_banExp").val(times)
                    }
                } else {
                    $("#edit_banExp").val("")
                }
            }
        }
    }

    function get_logs(uid) {
        $.ajax({
            cache: false,
            type: "POST",
            data: {
                act: "logs",
                id: uid
            },
            dataType: "json",
            success: function (data) {
                if (data.code == 200) {
                    add_logs(data.data.logs)
                } else {
                    cocoMessage.error(data.msg, 2000)
                }
            },
            error: function (XMLHttpRequest, textStatus, errorThrown) {
                cocoMessage.error(textStatus, 2000)
            }
        })
    }

    function add_logs(list) {
        if (list.length > 0) {
            $("#logs_state").attr("hidden", true);
            $("#logs_table").attr("hidden", false);
            $("#tbody_logs").empty();
            for (var i = 0; i < list.length; i++) {
                var lists = '<tr><td scope="col">' + list[i].actType + '<br /><span class="small text-muted">操作类型</span></td><td>' + list[i].time + '<br /><span class="small text-muted">' + list[i].ip + '</span></td><td><span class="dot dot-lg bg-' + (list[i].state == "y" ? "success" : "danger") + '"></span></td></tr>';
                $("#tbody_logs").append(lists)
            }
        } else {
            $("#logs_state").attr("hidden", false);
            $("#logs_table").attr("hidden", true)
        }
    }

    function add_client(list) {
        if (list.length > 0) {
            $("#client_state").attr("hidden", true);
            $("#client_table").attr("hidden", false);
            $("#tbody_client").empty();
            for (var i = 0; i < list.length; i++) {
                var lists = '<tr id="client_' + list[i].udid + '"><td class="text-left">' + list[i].udid + '<br /><span class="small text-muted">' + timeToDate(list[i].time) + '</span></td><td><a id="client_' + list[i].udid + '" href="javascript:del_client(\'' + list[i].udid + "');\">解绑</a></td></tr>";
                $("#tbody_client").append(lists)
            }
        } else {
            $("#client_state").attr("hidden", false);
            $("#client_table").attr("hidden", true)
        }
    }

    function del_client(cid) {
        var uid = $("#edit_id").val();
        $("#client_del_" + cid).html('<i class="spinner-ui fe fe-rotate-cw fe-12 mr-2"></i>');
        $("#logon_del_" + cid).attr("style", "pointer-events:none;");
        $.ajax({
            cache: false,
            type: "POST",
            data: {
                act: "del_client",
                id: uid,
                cid: cid
            },
            dataType: "json",
            success: function (data) {
                if (data.code == 200) {
                    $("#client_" + cid).remove();
                    cocoMessage.success(data.msg, 2000)
                } else {
                    $("#client_del_" + cid).html("解绑");
                    $("#client_del_" + cid).attr("style", "");
                    cocoMessage.error(data.msg, 2000)
                }
            },
            error: function (XMLHttpRequest, textStatus, errorThrown) {
                $("#client_del_" + cid).html("解绑");
                $("#client_del_" + cid).attr("style", "");
                cocoMessage.error(textStatus, 2000)
            }
        })
    }

    function valTotype(val) {
        var v;
        if (val == 9999999999) {
            return "永久"
        }
        if (val >= 86400) {
            v = val / 60 / 60 / 24;
            return (isInteger(v) ? v : v.toFixed(2)) + "天"
        }
        if (val >= 3600) {
            v = val / 60 / 60;
            return (isInteger(v) ? v : v.toFixed(2)) + "时"
        }
        if (val >= 60) {
            v = val / 60;
            return (isInteger(v) ? v : v.toFixed(2)) + "分"
        } else {
            return val + "秒"
        }
    }
</script>
<?php include_once 'footer.php'; ?>
